﻿using ICSharpCode.SharpZipLib.Zip;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Reflection;
using System.Runtime.Intrinsics.Arm;
using System.Text;
using System.Linq;
namespace Cyss.Core.Helper
{

    /// <summary>
    /// 文件操作帮助类
    /// </summary>
    public class FileHelper
    {
        /// <summary>
        /// 生成pdf文件
        /// </summary>
        /// <param name="stream">文件流</param>
        /// <param name="pdfName">pdf名称(不带后缀)</param>
        /// <param name="path">路径</param>
        public static void CreatePdf(Stream stream, string pdfName, string path = "")
        {
            CreateFile(stream.ToBytes(), pdfName, "pdf", path);
        }

        /// <summary>
        /// 生成pdf文件
        /// </summary>
        /// <param name="stream">文件流</param>
        /// <param name="pdfName">pdf名称(不带后缀)</param>
        /// <param name="path">路径</param>
        public static void CreatePng(Stream stream, string pdfName, string path = "")
        {
            CreateFile(stream.ToBytes(), pdfName, "png", path);
        }
        /// <summary>
        /// 生成pdf文件
        /// </summary>
        /// <param name="stream">文件流</param>
        /// <param name="pdfName">pdf名称(不带后缀)</param>
        /// <param name="path">路径</param>
        public static void CreateJpg(Stream stream, string pdfName, string path = "")
        {
            CreateFile(stream.ToBytes(), pdfName, "jpg", path);
        }
        /// <summary>
        /// 生成pdf文件
        /// </summary>
        /// <param name="bytes">文件流</param>
        /// <param name="pdfName">pdf名称(不带后缀)</param>
        /// <param name="path">路径</param>
        public static void CreatePdf(byte[] bytes, string pdfName, string path = "")
        {
            CreateFile(bytes, pdfName, "pdf", path);
        }
        private static void CreateFile(byte[] bytes, string pdfName, string suffix, string path = "")
        {
            if (!string.IsNullOrWhiteSpace(path))
            {
                if (!Directory.Exists(path))
                {
                    System.IO.Directory.CreateDirectory(path);
                }
            }
            else
            {
                path = AppDomain.CurrentDomain.BaseDirectory;
            }



            using (System.IO.FileStream fs = new System.IO.FileStream($"{path}/{pdfName}.{suffix}", System.IO.FileMode.CreateNew))
            {
                fs.Write(bytes, 0, bytes.Length);
            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="filePaths"></param>
        /// <returns></returns>
        public static byte[] ZipFileMain(string[] filePaths)
        {
            byte[] res;
            using (MemoryStream ms = new MemoryStream())
            {
                using (ZipArchive zip = new ZipArchive(ms, ZipArchiveMode.Create, true))
                {
                    foreach (var filepath in filePaths)
                    {
                        var pdfBytes = File.ReadAllBytes(filepath);
                        ZipArchiveEntry entry = zip.CreateEntry(Path.GetFileName(filepath));//压缩文件内创建一个文件名为“abc.pdf”,流是什么文件格式就用什么格式，此处我的是pdf格式
                        using (Stream sw = entry.Open())
                        {
                            sw.Write(pdfBytes, 0, pdfBytes.Length);//将文件的字节写到abc.pdf中
                        }
                    }
                    InvokeWriteFile(zip);//重新计算压缩文件的大小，此处参考别人的
                    int nowPos = (int)ms.Position;
                    res = new byte[ms.Length];
                    ms.Position = 0;
                    ms.Read(res, 0, res.Length);
                    ms.Position = nowPos;
                }
                return res;
            }

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="fileStreams"></param>
        /// <param name="fileNames"></param>
        /// <returns></returns>
        public static byte[] ZipFileMain(Stream[] fileStreams, string[] fileNames)
        {
            return ZipFileMain(fileStreams.Select(x => x.ToBytes()).ToArray(), fileNames);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="fileBytes"></param>
        /// <param name="fileNames"></param>
        /// <returns></returns>
        public static byte[] ZipFileMain(byte[][] fileBytes, string[] fileNames)
        {
            byte[] res;
            using (MemoryStream ms = new MemoryStream())
            {
                using (ZipArchive zip = new ZipArchive(ms, ZipArchiveMode.Create, true))
                {
                    int index = 0;
                    foreach (var fileByte in fileBytes)
                    {
                        ZipArchiveEntry entry = zip.CreateEntry(fileNames[index++]);//压缩文件内创建一个文件名为,流是什么文件格式就用什么格式，此处我的是pdf格式
                        using (Stream sw = entry.Open())
                        {
                            sw.Write(fileByte, 0, fileByte.Length);//将文件的字节写到abc.pdf中
                        }
                    }
                    InvokeWriteFile(zip);//重新计算压缩文件的大小，此处参考别人的
                    int nowPos = (int)ms.Position;
                    res = new byte[ms.Length];
                    ms.Position = 0;
                    ms.Read(res, 0, res.Length);
                    ms.Position = nowPos;
                }
                return res;
            }

        }

        private static void InvokeWriteFile(ZipArchive zipArchive)
        {
            foreach (MethodInfo method in zipArchive.GetType().GetRuntimeMethods())
            {
                if (method.Name == "WriteFile")
                {
                    method.Invoke(zipArchive, new object[0]);
                }
            }
        }

        /// <summary>
        /// Base64字符串转换成文件
        /// </summary>
        /// <param name="strInput">base64字符串</param>
        /// <param name="fileName">保存文件的绝对路径</param>
        /// <returns></returns>
        public static bool Base64ToFileAndSave(string strInput, string fileName)
        {
            bool bTrue = false;

            try
            {
                byte[] buffer = Convert.FromBase64String(strInput);
                FileStream fs = new FileStream(fileName, FileMode.CreateNew);
                fs.Write(buffer, 0, buffer.Length);
                fs.Close();
                bTrue = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return bTrue;
        }


        /// <summary>
        /// 解压字节
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static byte[] Decompress(byte[] bytes)
        {
            using (var compressStream = new MemoryStream(bytes))
            {
                using (var zipStream = new GZipStream(compressStream, CompressionMode.Decompress))
                {
                    using (var resultStream = new MemoryStream())
                    {
                        zipStream.CopyTo(resultStream);
                        return resultStream.ToArray();
                    }
                }
            }
        }

        /// <summary>
        /// 压缩
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static byte[] Compress(byte[] data)
        {
            try
            {
                MemoryStream ms = new MemoryStream();
                GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true);
                zip.Write(data, 0, data.Length);
                zip.Close();
                byte[] buffer = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(buffer, 0, buffer.Length);
                ms.Close();
                return buffer;

            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }
    }
}
